from django.shortcuts import render, redirect

from django.views import View
from django import http
from re import match
from django.contrib.auth import login, logout, authenticate
from django_redis import get_redis_connection
from django.conf import settings
# from django.contrib.auth.mixins import LoginRequiredMixin
from json import dumps, loads
# from django.core.mail import send_mail
from django.db import DatabaseError

from .models import User, Address
from csdp.utils.views import LoginRequiredView
from csdp.utils.response_code import RETCODE
from celery_tasks.email.tasks import send_verify_email
from .utils import generate_email_verify_url, get_user_token
import logging

logger = logging.getLogger('django')

# Create your views here.

class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        password2 = query_dict.get('password2')
        mobile = query_dict.get('mobile')
        sms_code = query_dict.get('sms_code')
        allow = query_dict.get('allow')
        list0 = query_dict.dict().values()
        if all(list0) is False or len(list0) != 6:
            return http.HttpResponseForbidden("参数错误。")
        if not match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('参数错误。')
        if not match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('参数错误。')
        if password2 != password:
            return http.HttpResponseForbidden('参数错误。')
        if not match(r'^1[345789]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数错误。')
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        redis_conn.delete('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'register.html', {'register_errmsg': '短信验证码已过期。'})
        sms_code_server = sms_code_server.decode()
        if sms_code != sms_code_server:
            return render(request, 'register.html', {'register_errmsg': '短信验证码填写错误。'})
        user = User.objects.create_user(username = username, password = password, mobile = mobile)
        login(request, user)
        response = redirect('/')
        response.set_cookie('username', user.username, max_age = settings.SESSION_COOKIE_AGE)
        return response


class UsernameCountView(View):
    def get(self, request, username):
        count = User.objects.filter(username = username).count()
        return http.JsonResponse({'count': count})


class MobileCountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile = mobile).count()
        return http.JsonResponse({'count': count})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        query_dict = request.POST
        username = query_dict.get('username')
        password = query_dict.get('password')
        remembered = query_dict.get('remembered')
        if all([username, password]) is False:
            return http.HttpResponse('参数错误。')

        # from django.db.models import Q
        # try:
        #     user = User.objects.get(Q(username = username) | Q(mobile = username))
        #     if user.check_password(password) is False:
        #         return render(request, 'login.html', {'account_errmsg': '用户名或密码错误。'})
        # except User.DoesNotExist:
        #     return render(request, 'login.html', {'account_errmsg': '用户名或密码错误。'})

        # try:
        #     if match('^1[3-9]\d{9}$', username):
        #         user = User.objects.get(mobile = username)
        #     else:
        #         user = User.objects.get(username = username)
        # except Exception as e:
        #     return render(request, 'login.html', {'account_errmsg': '用户名或密码错误。'})
        # if user.check_password(password) is False:
        #     return render(request, 'login.html', {'account_errmsg': '用户名或密码错误。'})

        user = authenticate(request, username = username, password = password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误。'})

        login(request, user)
        if remembered is None:
            request.session.set_expiry(0)
        response = redirect(request.GET.get('next') or '/')
        response.set_cookie('username', user.username, max_age = None if remembered is None else settings.SESSION_COOKIE_AGE)
        return response

class LogoutView(View):
    def get(self, request):
        logout(request)
        response = redirect('/')
        response.delete_cookie('username')
        return response


# class InfoView(View):
#     def get(self, request):
#         user = request.user
#         if user.is_authenticated:
#             return render(request, 'user_center_info.html')
#         else:
#             return redirect('/login/?next=/info/')


# from django.utils.decorators import method_decorator
# from django.contrib.auth.decorators import login_required
#
#
# class InfoView(View):
#     @method_decorator(login_required)
#     def get(self, request):
#         return render(request, 'user_center_info.html')


# class InfoView(LoginRequiredMixin, View):
class InfoView(LoginRequiredView):
    def get(self, request):
        return render(request, 'user_center_info.html')


class EmailView(LoginRequiredView):
    def put(self, request):
        email = loads(request.body.decode()).get('email')
        if not match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('邮箱不太行。')
        user = request.user
        if user.email != email:
            user.email = email
            user.save()
        # send_mail(
        #     subject = '?',
        #     message = '?',
        #     from_email = settings.EMAIL_FROM,
        #     recipient_list = [email],
        #     html_message = '<a href = "http://www.meiduo.site:8000">丑少当铺</a>',
        # )
        verify_url = generate_email_verify_url(user)
        send_verify_email(email, verify_url)
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class EmailVerifyView(View):
    def get(self, request):
        token = request.GET.get('token')
        user = get_user_token(token)
        if user is None:
            return http.HttpResponseForbidden('请重新验证。')
        user.email_active = True
        user.save()
        return redirect('/info/')


class AddressesView(LoginRequiredView):
    def get(self, request):
        user = request.user
        address_qs = Address.objects.filter(user = user, is_delete = False)
        address_list = []
        for address in address_qs:
            address_list.append({
                'id': address.id,
                'title': address.title,
                'receiver': address.receiver,
                'province_id': address.province_id,
                'province': address.province.name,
                'city_id': address.city_id,
                'city': address.city.name,
                'district_id': address.district_id,
                'district': address.district.name,
                'place': address.place,
                'mobile': address.mobile,
                'tel': address.tel,
                'email': address.email
            })
        return render(request, 'user_center_site.html', {
            'addresses': address_list,
            'default_address_id': user.default_address_id
        })


class AddressesCreateView(LoginRequiredView):
    def put(self, request):
        json_dict = loads(request.body.decode())
        title = json_dict.get('title')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        list0 = json_dict.dict().pop('tel').pop('email').values()
        if all(list0) is False or len(list0) != 7:
            return http.HttpResponseForbidden('参数错误。')
        if not match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数错误。')
        user = request.user
        try:
            address = Address(
                user = user,
                title=title,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )
            address.save()
        except DatabaseError as e:
            logger.error(e)
            return http.HttpResponseForbidden('参数错误。')
        if user.default_address is None:
            user.default_address = address
            user.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'address': {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province_id': address.province_id,
            'province': address.province.name,
            'city_id': address.city_id,
            'city': address.city.name,
            'district_id': address.district_id,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }})
